/***************************************************************************
 *   Copyright (C) 2008 by Rysiek Krol
 *   rysiek@Babylon2   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "eventhandler.h"

#include <QLabel>
#include <QEvent>
#include <QPixmap>
#include <QImage>
#include <QStatusBar>

#include "picturemanager.h"
#include "viewerevent.h"
#include "updateiconevent.h"
#include "imageloadedevent.h"
#include "displayoperations.h"
#include "imageloader.h"
#include "imagereader.h"
#include "utils.h"


EventHandler::EventHandler(PictureManager *manager) : QObject(), manager(manager)
{
}

EventHandler::~EventHandler()
{
}

void EventHandler::handleEvent(QEvent * event)
{
    switch (event->type())
    {
    case ViewerEvent::ListRefreshNeeded:

        this->handleListRefreshNeededEvent();
        break;
    case ViewerEvent::UpdateIcon:
    {
        this->handleUpdateIconEvent(dynamic_cast<UpdateIconEvent*>(event));
        break;
    }
    break;
    case ViewerEvent::LoadedImageEvent:
    {
        this->handleLoadedImageEvent( dynamic_cast<ImageLoadedEvent*> (event));

    }
    break;
    case ViewerEvent::iconGenerationCompleateEvent:
        this->handleIconGenerationCompleateEvent();
        break;
    case ViewerEvent::NewSearchEvent:
        this->manager->getDisplayOperations()->searchSlot();
        break;
    case ViewerEvent::FileOperationError: {
	FileOperationErrorEvent *errorEvent = dynamic_cast<FileOperationErrorEvent*>(event);
        this->manager->getDisplayOperations()->handleFileOperationError(errorEvent);
	}
    default:
        QMainWindow ( event );
        break;
    }
}

/**
  * Handles custom event
  */
void EventHandler::customEvent(QEvent * event)
{
    this->handleEvent(event);
}

/*
 * Handles Update Icon Event. Sets new Icon and refresh browser
 */
void EventHandler::handleUpdateIconEvent(UpdateIconEvent * event)
{
    if (event->getUpdateType() == UpdateIconEvent::IconToUpdate)
    {
        QFileInfo * info = event->file();
        PictureListWidgetItem* item = dynamic_cast<PictureListWidgetItem*>(this->manager->listWidget->item(this->manager->findItem(info)));
        item->setIcon(QIcon(QPixmap::fromImage(Utils::generateIcon(*info))));
        this->manager->listWidget->update();
    }
    else
    {
        if ( this->manager->listWidget->count() >0 )
        {
            UpdateIconEvent *updateEvent = dynamic_cast<UpdateIconEvent*> (event );
            if (updateEvent->getItem()->getFile().isDir())
            {
	       QSize iconSize(36, 36);
	       
		
               updateEvent->getItem()->setIcon( this->manager->getStyl()->standardIcon(QStyle::SP_DirIcon).pixmap(iconSize));

	       //updateEvent->getItem()->setIcon (QPixmap::fromImage(*updateEvent->getIcon()));
            }
            else
            {
                updateEvent->getItem()->setIcon (QPixmap::fromImage(*updateEvent->getIcon()));
            }
            this->manager->listWidget->update();
        }
    }
}

/**
  * Refresh Browser window
  */
void EventHandler::handleListRefreshNeededEvent()
{
    QListWidget *itsListWidget = this->manager->listWidget;
    itsListWidget->update();
    QFileInfo file = this->manager->itsProperty->getCurrentItem();
    int itemIndex = this->manager->findItem(&file);
    if (itemIndex >= 0)
    {
        QListWidgetItem *item = this->manager->listWidget->item(itemIndex);
        itsListWidget->scrollToItem(item,QAbstractItemView::PositionAtCenter);
        itsListWidget->setCurrentItem(item);
    }
}

/**
  * Handles Loaded image event, sends image to display method and sets status on the status bar
  */
void EventHandler::handleLoadedImageEvent(ImageLoadedEvent * event)
{
    if (!this->manager->displayOperations->getIsSlideShowActive())
    {
        this->manager->presentationWidget->setToolTip(this->manager->listWidget->item(event->getImageIndex())->toolTip());
        PictureListWidgetItem *item = (dynamic_cast<PictureListWidgetItem*>(this->manager->listWidget->item(event->getImageIndex())));
        this->manager->listWidget->setCurrentItem(item);
        this->manager->setWindowTitle(tr("AliceViewer: ") + item->getFile().absoluteFilePath() );
    }
    else
    {
        QFileInfo *info = new QFileInfo(this->manager->itsLoader->getCurrentSlide());
        PictureListWidgetItem *item = new PictureListWidgetItem(*info);
        this->manager->presentationWidget->setToolTip(item->toolTip());
        this->manager->setWindowTitle(tr("AliceViewer: ") + item->getFile().absoluteFilePath() );
        delete item;
        delete info;
    }
    this->manager->displayImage(QPixmap::fromImage(event->getImage()));
    this->manager->statusBar()->showMessage( tr("Image ") +
                                             QString::number(event->getImageIndex()) +
                                             "/" +
                                             QString::number(event->getImageCount()));

}

/**
  * Handles iconGenerationCompleate event. Starts reader threat and udates Window title
  * this handler is used to start reader once more, when user change directory before reader can generate all
  * icons from old dir
  */
void EventHandler::handleIconGenerationCompleateEvent()
{
    this->manager->listWidget->clear();
    this->manager->itsReader->setDir(this->manager->curDir);
    this->manager->itsReader->readDirCondition.wakeAll();
    this->manager->setWindowTitle(tr("AliceViewer: ") + this->manager->curDir->absolutePath() );
}


